package com.example.bookshop.service.user;

import com.example.bookshop.entity.BaseGoods;
import com.example.bookshop.entity.Business;
import com.example.bookshop.entity.Goods;
import com.example.bookshop.repository.BusinessRepository;
import com.example.bookshop.repository.GoodsRepository;
import com.example.bookshop.result.Result;
import com.example.bookshop.util.MyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService{
    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private BusinessRepository businessRepository;

    @Override
    public List<BaseGoods> getListGoods() {
        return goodsRepository.findAllGoods();
    }

    @Override
    public List<BaseGoods> getCategoryGoods(String category, String state) {
        if(category.equalsIgnoreCase("0")){
            return goodsRepository.findAllGoods();
        }
        else return goodsRepository.findGoodsByByCategoryAndState(category,state);
    }

    @Override
    public Goods findGoodsDetail(Integer id) {
        return goodsRepository.findGoodsById(id);
    }

    @Override
    public Result addGoods(Goods goods, HttpSession session) {
        MyUtil myUtil=new MyUtil();
        Integer id=myUtil.getUserId(session);
        Business business=businessRepository.findBusinessByUserId(id);
        Integer businessId=business.getId();
        goods.setBusinessId(businessId);
        int i=goodsRepository.addGoods(goods);
        if(i==0){
            return new Result(400);
        }
        if(i==1){
            return new Result(200);
        }
        else
            return new Result(300);
    }

    @Override
    public List<BaseGoods> findGoodsByMall(HttpSession session) {
        MyUtil myUtil=new MyUtil();
        int businessId=businessRepository.findBusinessByUserId(myUtil.getUserId(session)).getId();
        return goodsRepository.findGoodsByBusinessId(businessId);
    }

    @Override
    public Result modifyGoods(Goods goods) {
       int i=goodsRepository.updateGoods(goods);
       if(i==1){
           return new Result(200);
       }
       else
           return new Result(400);
    }

    @Override
    public Result deleteGoods(Integer id) {
        int i=goodsRepository.deleteGoods(id);
        if(i==1){
            return new Result(200);
        }
        else return new Result(400);
    }

    @Override
    public List<BaseGoods> searchGoods(Goods goods) {
        return goodsRepository.findGoodsByName(goods.getGoodsName());
    }

}
